package controller;

import dao.OrderDao;
import dao.UserDao;
import org.apache.ibatis.session.SqlSession;
import pojo.Order;
import pojo.User;
import utils.MyBatisUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

/**
 * @author HLF
 * @date 2022/6/14 12:15
 */
@WebServlet("/userController")
public class UserController extends BaseController {

    /**
     * 获取用户列表
     */
    public List<User> list() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);

        List<User> users = userDao.getAllUsers();
        sqlSession.close();
        return users;
    }

    /**
     * 跳转到用户管理页面
     */
    protected void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<User> users = this.list();
        req.setAttribute("users", users);

        req.getRequestDispatcher("/userManage.jsp").forward(req, resp);
    }

    /**
     * 登录
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        String code = req.getParameter("code");

        //获取session中的验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //删除session中的验证码，防止下次重复使用
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);

        //2.检查验证码是否正确
        if (token.equalsIgnoreCase(code)) {

            SqlSession sqlSession = MyBatisUtil.getSqlSession();
            UserDao userDao = sqlSession.getMapper(UserDao.class);

            User user = userDao.loginUser(new User(null, username, password));
            if (user != null) {
                req.getSession().setAttribute("user", user);
                req.getRequestDispatcher("/index.jsp").forward(req, resp);
            } else {
                req.setAttribute("msg", "用户名或密码错误！");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
        } else {//验证码错误
            req.setAttribute("msg", "验证码错误");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }

    /**
     * 注册
     */
    protected void regist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);

        User byUsername = userDao.getByUsername(username);
        if (byUsername == null) {
            int i = userDao.insertUser(new User(null, username, password));
            sqlSession.commit();

            if (i > 0) {
                req.setAttribute("msg", "注册成功，请登录！");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            } else {
                req.setAttribute("msg", "注册失败！");
                req.getRequestDispatcher("/register.jsp").forward(req, resp);
            }
        } else {
            req.setAttribute("msg", "用户名已被注册！");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
        }

        sqlSession.close();
    }

    /**
     * 添加用户
     */
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);

        int i = userDao.insertUser(new User(null, username, password));
        sqlSession.commit();


        sqlSession.close();
        this.index(req, resp);//重新跳转到用户管理页面
    }

    /**
     * 修改用户
     */
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uid = req.getParameter("uid");
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);

        userDao.updateUser(new User(Integer.valueOf(uid), username, password));

        sqlSession.commit();
        sqlSession.close();
        this.index(req, resp);//重新跳转到用户管理页面
    }

    /**
     * 根据uid获取用户
     */
    protected void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uid = req.getParameter("uid");
        resp.setContentType("text/html;charset=UTF-8");

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);

        User user = userDao.getByUid(Integer.valueOf(uid));

        req.setAttribute("quser", user);

        this.index(req, resp);
    }

    /**
     * 删除用户
     */
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uid = req.getParameter("uid");
        resp.setContentType("text/html;charset=UTF-8");

        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserDao userDao = sqlSession.getMapper(UserDao.class);
        OrderDao orderDao = sqlSession.getMapper(OrderDao.class);

        //删除之前先查看order中是否含有记录，如果有就禁止删除
        List<Order> allOrdersByUid = orderDao.getAllOrdersByUid(Integer.valueOf(uid));

        PrintWriter writer = resp.getWriter();
        if (allOrdersByUid.size() == 0) {
            userDao.deleteByUid(Integer.valueOf(uid));
            sqlSession.commit();
            writer.println("删除成功！");
            writer.flush();
        } else {
            writer.println("删除失败，请先处理相关预约记录！");
            writer.flush();
        }

        sqlSession.close();
    }

    /**
     * 退出登录
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        session.removeAttribute("user");

        req.getRequestDispatcher("/login.jsp").forward(req, resp);
    }
}
